/*
    Copyright (c) Guangzhou Data Control Network Technology Co., Ltd. All rights reserved.
    Licensed under the MIT License.
    contact:dcdev_founder@foxmail.com
*/
function showImageCuter(showImageCuterData, data, callback) {
  // $.get(site_config.api_host + "get_access_token.php", function (res) {
  // });
  window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", judge, false);
  function judge() {
    if (window.orientation == 90 || window.orientation == -90) {
      setTimeout(function () {
        parent.$('.layui-layer-content').css({ 'padding': '10px 20px', 'height': '500px', 'overflow-y': 'auto', "overflow-x": "hidden", "width": "75%" });
        parent.$('.layui-layer-dialog').css({ 'width': '100%', 'height': '100%', 'top': '0', 'left': '0', "overflow": "auto" })
      }, 400);
    } else if (window.orientation == 0) {
      setTimeout(function () {
        parent.$('.layui-layer-content').css('padding', '10px').css('overflow', 'hidden').css('height', '555px').css("width", "auto");
        parent.$('.layui-layer-dialog').css({ 'width': '100%', 'height': '100%', 'top': '0', 'left': '0' })
      }, 400);
    }
  }
  //根据data引用方法
  var change = false;
  layui.use('layer', function () {
    var layer = layui.layer;
    var w = "700px",
      h = "500px";
    if (browser_info.is_mobile) {
      w = window.screen.width - 30 + 'px', h = "";
    }
    window.parent.layer.open({
      type: 0,
      title: false //不显示标题栏
      ,
      closeBtn: false,
      area: [w, h],
      shade: 0.8,
      id: 'LAY_layuipro66' //设定一个id，防止重复弹出
      ,
      moveType: 1 //拖拽模式，0或者1
      ,
      content: `<div class="dcdev-image11">
        <div class="dcdev-image09"></div>
        <div class="tailoring-content">
          <!-- <div class="tailoring-content-one">
            <div class="dcdev-image04">
              <i></i>
            </div>
          </div> -->
          <div class="tailoring-content-two">
            <div class="leftContent" style="border-right: 1px solid #ddd;width: 490px;height: 390px;float: left;margin-bottom: 10px;">
                <div class="tailoring-box-parcel">
                <img id="tailoringImg">
                </div>
            </div>
            <div>
                <div class="preview-box-parcel">
                    <div>
                        <div class="circular previewImg"></div>
                    </div>
                </div>
            </div>
          </div>
          <div class="tailoring-content-three">
            <label class="dcdev-image10" style="background-color: white;padding:0;">
              <input type="file" class="dcdev-image05">
              <i style="color:#1E9FFF;"></i>
            </label>
            <!-- <button class="layui-btn cropper-reset-btn">复位</button> -->
            <button class="dcdev-image06" style="background-color: white;padding:0;margin-left:30px;"><i style="color:#1E9FFF;"></i></button>
            <button class="dcdev-image07" style="background-color: white;padding:0;margin-left:30px;"><i style="color:#1E9FFF;"></i></button>
          </div>
          <div class="imgSelector_submitBtn" style="text-align:right;">
            <button class="layui-btn layui-btn-normal"  id="sureCut">确定</button>
            <button class="layui-btn layui-btn-primary"  id="refuse">取消</button>
          </div>
        </div>
      </div>`,
      success: function (layero, index) {
        parent.$('.layui-layer-content').css('padding', '10px').css('overflow', 'hidden').css('height', '500px');
        parent.$('.layui-layer-btn').remove();
        parent.$('.dcdev-image01').addClass('layui-elem-field layui-field-title').css('margin-top', '30px')
        parent.$('.dcdev-image02').css("position", "relative").children('img').css({ "display": "none", 'width': "250px", 'height': "200px", "border": "solid 1px #cacaca" })
        parent.$('.dcdev-image03').css({ "padding": "0px", "padding-top": "50px", "box-sizing": "border-box" }).css("padding-top", "50px").children('i').addClass('layui-icon layui-icon-picture-fine').css({ 'font-size': '60px' })
        parent.$('.dcdev-image04').addClass('close-size').css({ "margin-right": "10px", "display": "block", "float": "right", "position": "absolute", "right": "0", "cursor": "pointer" }).children('i').addClass('layui-icon layui-icon-close')
        parent.$('.dcdev-image05').addClass('hidden').next('i').addClass('layui-icon layui-icon-picture')
        parent.$('.dcdev-image06').addClass('layui-btn cropper-rotate-btn').children('i').addClass('layui-icon layui-icon-refresh-1')
        parent.$('.dcdev-image07').addClass('layui-btn cropper-scaleX-btn').children('i').addClass('layui-icon layui-icon-rate-half')
        parent.$('.dcdev-image09').addClass('black-cloth')
        parent.$('.dcdev-image10').addClass('layui-btn')
        parent.$(".layui-btn .layui-icon").css({ "font-size": "26px" });
        if (browser_info.is_mobile) {
          parent.$('.layui-layer-dialog').css({ 'width': '100%', 'height': '100%', 'top': '0', 'left': '0' })
          parent.$('.leftContent').css('height', '')
          parent.$('.tailoring-container .tailoring-content').css('width', '100%');
          parent.$('.leftContent').css('border-right', '').css('float', '').css('width', '100%').css('border-left', '').css('margin-bottom', '');
          parent.$('.tailoring-content .tailoring-box-parcel').css('width', '100%');
          parent.$('.preview-box-parcel').find('div').eq(0).css('margin-bottom', '').css('border-bottom', '').css('width', '').css('height', '').css('float', 'left').css('margin-top', '');
          parent.$('.preview-box-parcel .square').css('width', '50px !important').css('height', '50px !important').css('border', '');
          parent.$('.circular').parent().css('float', 'left');
          parent.$('.preview-box-parcel .circular').css('width', '50px !important').css('height', '50px !important');
          parent.$('.leftContent').next().css('border-bottom', '1px solid #ddd');
          parent.$('.preview-box-parcel .circular').css('margin-top', '0px');
          parent.$(".preview-box-parcel div").css({ "float": "right", "margin-left": "10px" });
          parent.$(".tailoring-content-three").css({ "padding-top": "15px", "display": "flex", "align-items": "center" });
          parent.$(".imgSelector_submitBtn").css("margin-top", "26px");
          parent.$(".layui-btn .layui-icon").css({ "margin-right": "0", "font-size": "26px" });
        }
        $(".uploadorigin").on("input", function (e) {
          //获取input输入的值
          var imagetypeurl = e.delegateTarget.value
          console.log(imagetypeurl)
          sessionStorage.setItem("imagetypeurl", imagetypeurl)
        });
        //image.js
        //弹出框水平垂直居中
        (window.onresize = function () {
          var win_height = $(window).height();
          var win_width = $(window).width();
          if (win_width <= 768) {
            parent.$(".tailoring-content").css({
              "top": (win_height - $(".tailoring-content").outerHeight()) / 2,
              "left": 0
            });
          } else {
            parent.$(".tailoring-content").css({
              "top": (win_height - $(".tailoring-content").outerHeight()) / 2,
              "left": (win_width - $(".tailoring-content").outerWidth()) / 2
            });
          }
        })();
        //图像上传
        parent.$('.dcdev-image10').click()
        function selectImg(file) {
          if (!file.files || !file.files[0]) {
            return;
          }
          var reader = new FileReader();
          reader.onload = function (evt) {
            var replaceSrc = evt.target.result;
            //更换cropper的图片
            parent.$('#tailoringImg').cropper('replace', replaceSrc, false); //默认false，适应高度，不失真
          }
          reader.readAsDataURL(file.files[0]);
        }
        parent.$('.dcdev-image05').bind('change', function () {
          selectImg(this)
        })
        var cropperSet = {
          preview: '.previewImg', //预览视图
          guides: false, //裁剪框的虚线(九宫格)
          autoCropArea: 1, //0-1之间的数值，定义自动剪裁区域的大小，默认0.8
          movable: false, //是否允许移动图片
          dragCrop: false, //是否允许移除当前的剪裁框，并通过拖动来新建一个剪裁框区域
          movable: false, //是否允许移动剪裁框
          maxHeight: 200,
          maxWidth: 200,
          height: 200,
          width: 200,
          resizable: true, //是否允许改变裁剪框的大小
          zoomable: true, //是否允许缩放图片大小
          mouseWheelZoom: false, //是否允许通过鼠标滚轮来缩放图片
          touchDragZoom: true, //是否允许通过触摸移动来缩放图片
          rotatable: true, //是否允许旋转图片
          setData: { width: 200, height: 100 },
          crop: function (e) {
            if (showImageCuterData.maxwidth) {
              if (e.detail.width > showImageCuterData.maxwidth) {
                aspectRatio_width = showImageCuterData.maxwidth;
              } else {
                aspectRatio_width = e.detail.width;
              }
            } else {
              if (e.detail.width > 1000) {
                aspectRatio_width = 1000;
              } else {
                aspectRatio_width = e.detail.width;
              }
            }
            if (showImageCuterData.maxheight) {
              if (e.detail.height > showImageCuterData.maxheight) {
                aspectRatio_height = showImageCuterData.maxheight;
              } else {
                aspectRatio_height = e.detail.height;
              }
            } else {
              if (e.detail.height > 1000) {
                aspectRatio_height = 1000;
              } else {
                aspectRatio_height = e.detail.height;
              }
            }
          }
        }
        Object.assign(cropperSet, showImageCuterData)
        //cropper图片裁剪
        parent.$('#tailoringImg').cropper(cropperSet);
        console.log(cropperSet)
        //旋转
        parent.$(".cropper-rotate-btn").on("click", function () {
          parent.$('#tailoringImg').cropper("rotate", 45);
        });
        //复位
        parent.$(".cropper-reset-btn").on("click", function () {
          parent.$('#tailoringImg').cropper("reset");
        });
        //换向
        var flagX = true;
        parent.$(".cropper-scaleX-btn").on("click", function () {
          if (flagX) {
            parent.$('#tailoringImg').cropper("scaleX", -1);
            flagX = false;
          } else {
            parent.$('#tailoringImg').cropper("scaleX", 1);
            flagX = true;
          }
          flagX != flagX;
        });
        //裁剪后的处理
        parent.$("#sureCut").on("click", function () {
          if (data != "") {
            if (data.rule.sub_type == 'html_bg') {
              var cas = parent.$('#tailoringImg').cropper('getCroppedCanvas', { width: aspectRatio_width, height: aspectRatio_height }); //获取被裁剪后的canvas
              var copperphotoImgUrl = cas.toDataURL('image/jpeg');

              url = "https://www.dcdev.net/" + "lib/lib_of_back_end/v1.0.1/api/dcdev/upload/upload_image_base64.php";
              data = { "upload_img": copperphotoImgUrl, 'pid': "0000000000000000" };
              $.ajax({
                method: "post",
                url: url,
                data: { params: JSON.stringify(data) },
                success: function (_result) {
                  var result = JSON.parse(_result);
                  if (result["res"] == 0) {
                    ui_class.show_error(result['tips'] ? result['tips'] : result['desc']);
                  } else {

                    var copperphotoImgUrl = "https://www.dcdev.net/" + result["data"].url;
                    data.rule.text = data.rule.text.replace('https://www.w3school.com.cn/i/eg_tulip.jpg', copperphotoImgUrl);
                    data.rule.text = data.rule.text.replace('min-width', ' ')
                    data.rule.text = data.rule.text.replace('height', ' ')

                    url = "https://api.dcdev.net/v1.0.1/column/insert_column.php";
                    $.ajax({
                      method: "post",
                      url: url,
                      data: { params: JSON.stringify(data) },
                      success: function (_res) {
                        layui.use(['layer'], function () {
                          res = JSON.parse(_res)

                          if (res['res'] == 0) {
                            ui_class.show_error(res['tips'] ? res['tips'] : res['desc']);
                          } else {
                            if (res.res) {
                              ui_class.show_success("添加成功");
                              var _body = window.parent;
                              var _iframe1 = _body.document.getElementById('setColumnIframe');
                              _iframe1.contentWindow.location.reload(true);
                              parent.$("iframe[id='showSetColumn']").attr('src', '../../../lib_of_front_end/dcdev/components/insert_class_data/insert_class_data.html?cid=' + cid)
                            } else {
                              ui_class.show_error(res.tips);
                            }
                          }
                        })
                      }
                    })
                  }
                }
              })
            }
          } else {
            if (parent.$("#tailoringImg").attr("src") == null) {
              return false;
            } else {
              if (change == true) {
                parent.$('#tailoringImg').cropper("setData", { width: 120, height: 120 });
              }
              var cas = parent.$('#tailoringImg').cropper('getCroppedCanvas', { width: aspectRatio_width, height: aspectRatio_height }); //获取被裁剪后的canvas
              var base64url = cas.toDataURL('image/jpeg'); //转换为base64地址形式

              $("#finalImg").prop("src", base64url); //显示为图片的形式
              // sessionStorage.setItem("finalImg", base64url)
              $("#finalImg").css("display", "block");
              // $("#replaceImg").css("display", "none");
              // uploadFile(encodeURIComponent(base64url))//编码后上传服务器 

              url = "https://www.dcdev.net/" + "lib/lib_of_back_end/v1.0.1/api/dcdev/upload/upload_image_base64.php";
              data = { "upload_img": base64url, 'pid': "0000000000000000" };
              $.ajax({
                method: "post",
                url: url,
                data: { params: JSON.stringify(data) },
                success: function (_result) {
                  var result = JSON.parse(_result);
                  if (result["res"] == 0) {
                    ui_class.show_error(result['tips'] ? result['tips'] : result['desc']);
                  } else {
                    // var sessionStorage_api_host = site_config.api_host.substring(0, site_config.api_host.length - 1);
                    // var uploadImg = sessionStorage_api_host + result["data"].url;
                    returnResult(result, callback)
                  }
                  uiClass.hideLoading();
                }
              })
              closeTailor();
            }
          }
          parent.layer.close(index);
        });
        //关闭裁剪框
        function closeTailor() {
          parent.layer.close(index);
          parent.$(".tailoring-container").toggle();
        }

        parent.$('.dcdev-image09,.dcdev-image04,#refuse').click(closeTailor)
      }
    });
  })
  // showCropper(showImageCuterData, data);
}

function returnResult(data, callback) {
  return callback(data);
}